import re

from django.contrib.auth.backends import ModelBackend
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from users.models import User

from django.conf import settings
from . import constants

def check_verify_email_token(token):
    """
    反序列化token，获取user
    :param token:
    :return: user
    """
    s = Serializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    try:
        data = s.loads(token)
    except BadData:
        return None
    else:
        user_id = data.get('user_id')
        email = data.get('email')
        try:
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            return None
        else:
            return user

def generate_verify_email_url(user):
    """ 邮箱激活链接 """
    s = Serializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    data = {'user_id': user.id, 'email': user.email}
    token = s.dumps(data).decode()
    return f"{settings.EMAIL_VERIFY_URL}?token={token}"


def get_user_by_account(account):
    """
    通过账号获取user
    :param account: 用户名或邮箱或手机号
    :return: user
    """
    try:
        if re.match(r'^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', account):
            user = User.objects.get(email=account)
        elif re.match(r'^1[3-9]\d{9}', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameEmailBackend(ModelBackend):
    """ 自定义用户认证后端口 """

    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        重写认证方法
        :param request:
        :param username: 用户名或邮箱或手机号
        :param password: 密码
        :param kwargs:
        :return: user
        """
        user = get_user_by_account(username)
        if user and user.check_password(password):
            return user
        else:
            return None



